package com.broada.apm.logic.impl;

import java.util.List;
import java.util.Set;

import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.base.BaseLogic;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.indicator.api.model.SearchCondition;
import com.broada.apm.indicator.api.model.SearchConditionComparator;
import com.broada.apm.indicator.api.util.AggregationUtil;
import com.broada.apm.logic.ServicePerformanceLogic;
import com.broada.apm.model.PerformanceView;
import com.broada.apm.utils.ExceptionUtils;

public class ServicePerformanceLogicImpl extends BaseLogic implements ServicePerformanceLogic {
	
	Logger log = LoggerFactory.getLogger(ServicePerformanceLogicImpl.class);

	@Override
	public List<PerformanceView> getServicePerformances(String ip, String serviceType, int focus, int serverity, long startDate,
			long endDate, Set<String> servIdList) {
		SearchCondition con = SearchCondition.newBuilder();
		con.add("agentStartTime", SearchConditionComparator.LEFTBETWEEN, startDate, endDate);
		
		if (servIdList.size() > 0) {
			con.add("agentId", SearchConditionComparator.IN, servIdList.toArray(new String[servIdList.size()]));
		}
		TermsBuilder aggs = AggregationUtil.getTerms("agentId", "agentId", 1000);
		aggs.subAggregation(AggregationUtil.getTerms("serviceType", "serviceType")); // 节点类型，agent接入的数据需要和协议分析器的统一
		aggs.subAggregation(AggregationUtil.getTerms("agentFlag", "agentFlag")); // 节点来源
		aggs.subAggregation(AggregationUtil.getSum("system/throughput/total", "_index")); // 吞吐量
		aggs.subAggregation(AggregationUtil.getAvg("system/response_time/avg", "elapsed")); // 平均响应时间
		aggs.subAggregation(AggregationUtil.getFilter("system/error/count", "transactionFlag", new String[]{"1", "3"})); // 错误数
		aggs.subAggregation(AggregationUtil.getMax("timestamp", "agentStartTime")); // 最后更新时间

		List<PerformanceView> staticPerf = null;
		try {
			staticPerf = queryPerfService.queryAggregationTermsPerf(con.add(aggs));
		} catch (ApmDataIndicatorException e) {
			ExceptionUtils.error(log, "查询性能数据失败", e);
		}
		return staticPerf;
	}

}
